package com.uyayo.oms.blog.controller;

import com.uyayo.blog.entity.BlogTag;
import com.uyayo.blog.model.BlogTagCondition;
import com.uyayo.blog.service.BlogTagService;
import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.Pageable;
import com.uyayo.framework.pagehelper.SortOrder;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.oms.blog.vo.BlogTagVO;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.system.authority.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * BlogController
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Controller("omsBlogTagController")
@RequestMapping("/oms/blog/tag")
public class BlogTagController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final ParamBiz paramBiz;

	private final BlogTagService blogTagService;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	@Autowired
	public BlogTagController(BlogTagService blogTagService, ParamBiz paramBiz, MessageSource messageSource, DozerBeanMapper dozerBeanMapper) {
		this.blogTagService = blogTagService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
	}

	/**
	 * 页面跳转
	 */
	@RequestMapping(value={"index","/","home"},method=RequestMethod.GET)
	@RequiresPermissions("oms:blog:content:index")
	public ModelAndView index(ModelAndView modelAndView) throws Exception {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/tag/index");
		return modelAndView;
	}

	/**
	 * 获得模型列表
	 */
	@ResponseBody
	@RequestMapping("list")
	@RequiresPermissions("oms:blog:tag:search")
	@MethodName(value="博客管理->博客标签管理->查询列表",type=2)
	public List<BlogTag> list(BlogTagCondition blogTagCondition) {
		return blogTagService.selectBlogTag(blogTagCondition);
	}

	@ResponseBody
	@RequestMapping(value="search",method=RequestMethod.GET)
	@MethodName(value="博客管理->博客标签管理->搜索",type=2)
	@RequiresPermissions("oms:blog:tag:search")
	public PageResult<BlogTag> selectblogTag(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第几页
										  @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,
											 String sort, String order, BlogTagCondition blogTagCondition) throws Exception {
		PageBean<BlogTag> pageBean= new PageBean<>();
		try {
			Pageable<BlogTagCondition> pageable  = new Pageable<>();
			List<SortOrder> sortOrders = new ArrayList<>();
			sortOrders.add(new SortOrder(sort,order));
			pageable.setCurrentPage((start / pageSize) + 1);
			pageable.setPageSize(pageSize);
			pageable.setSortOrders(sortOrders);
			pageable.setCondition(blogTagCondition);
			pageBean = blogTagService.selectBlogTagByPaging(pageable);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageResult<BlogTag> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
	}

	/**
	 * 进入新增表单
	 */
	@RequiresPermissions("oms:blog:tag:create")
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return paramBiz.getManagerTemplatesPrefix()+"blog/tag/add";
	}

	/**
	 * 新建
	 */
	@ResponseBody
	@RequiresPermissions("oms:blog:tag:create")
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@MethodName(value="博客管理->博客标签管理->新增",type=2)
	synchronized public Result add(HttpServletRequest request, BlogTagVO blogTagVO, Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			BlogTag blogTag = dozerBeanMapper.map(blogTagVO,BlogTag.class);
			blogTag.setCreateTime(new Date());
			blogTag.setCreateBy(sysUser.getLoginname());
			int countSave = blogTagService.saveBlogTag(blogTag);
			if(countSave<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500, message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}


	/**
	 * 进入查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="博客管理->博客标签管理->查看",type=2)
	@RequiresPermissions("oms:blog:tag:view")
	public ModelAndView view(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		try {
			BlogTag blogTag = blogTagService.selectByKey(id);
			modelAndView.addObject("blogTag",blogTag);
			modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/tag/view");
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("oms:blog:tag:update")
	public ModelAndView update(ModelAndView modelAndView, HttpServletRequest request, Long id) {
		try {
			BlogTag blogTag= blogTagService.selectByKey(id);
			modelAndView.addObject("blogTag",blogTag);
			modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/tag/update");
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		return modelAndView;
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("update")
	@RequiresPermissions("oms:blog:tag:update")
	@MethodName(value="博客管理->博客标签管理->修改",type=2)
	synchronized public Result updateIcon(HttpServletRequest request, BlogTagVO blogTagVO, Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();

			BlogTag blogTag = dozerBeanMapper.map(blogTagVO,BlogTag.class);
			blogTag.setUpdateTime(new Date());
			blogTag.setUpdateBy(sysUser.getLoginname());
			int count = blogTagService.updateBlogTag(blogTag);
			if(count<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500, message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}

	/**
	 * 删除图标
	 */
	@ResponseBody
	@RequestMapping("delete")
	@RequiresPermissions("oms:blog:tag:delete")
	@MethodName(value="博客管理->博客标签管理->删除",type=2)
	public Result deleteArticle(HttpServletRequest request, Long id) {
		try {
			if (id==null) {
				String message = messageSource.getMessage("parameter.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
			int deleteCount = blogTagService.delete(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage("delete.fail",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500,message);
		}
		String message = messageSource.getMessage("delete.success",new Object[]{}, request.getLocale());
		logger.info(message);
		return Result.success(200,message);

	}
}
